<?php
namespace app\api\controller;

use app\common\controller\Api;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;

class OwnerAudit extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 获取列表获取车主审核列表
     *
     * @return void
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getList()
    {
        $type = $this->request->get('type');
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $uid = $this->auth->id;

        if (!$uid) {
            $this->error('请先登录');
        }

        if (!$type || !$page || !$limit) {
            $this->error('参数错误');
        }

        $projectManager = (new \app\admin\model\ProjectManager())->where('uid', $uid)->find();
        // 根据 type 确定 status
        $status = $type;
        $model = new \app\admin\model\OwnerAudit();
        // 查询列表数据
        $list = $model->where('status', $status)
                      ->where('project_manager_id', $projectManager->id)
                      ->order('id', 'desc')
                      ->page($page)
                      ->limit($limit)
                      ->select()->toArray();
        foreach ($list as $key => $value) {
            $owner = (new \app\admin\model\Owner())->where('id', $value['owner_id'])->find();
            $list[$key]['owner'] = $owner;
            $list[$key]['project_name'] = (new \app\admin\model\Project())->where('id', $value['project_id'])->value('name');
            $list[$key]['car_counts'] = (new \app\admin\model\Car())->where('uid', $owner->uid)->count();
        }
        // 查询总数
        $count = $model->where('status', $status)->where('project_manager_id', $projectManager->id)->count();

        $data = [
            'list' => $list,
            'count' => $count,
        ];
        $this->success('获取成功', $data);
    }

    /**
     * 审核车主申请
     *
     * @return void
     */
    public function audit()
    {
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        if (!$id || !$status) {
            $this->error('参数错误');
        }
        $model = new \app\admin\model\OwnerAudit();
        $res = $model->where('id', $id)->update(['status' => $status]);
        if ($res) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }
}